<?php

  /**
   *
   */
class Cicp_StorageDriver_Filesystem implements Cicp_StorageDriver_Interface
{
    private $_graphDirectory = 'cicp_files/storage/graphs/';
    private $_gdfDirectory = 'cicp_files/storage/gdf/';

    function __construct()
    {
        $this->createDirectory($this->_graphDirectory);
        $this->createDirectory($this->_gdfDirectory);
        $this->_graphDirectory = realpath($this->_graphDirectory) . '/';
        $this->_gdfDirectory = realpath($this->_gdfDirectory) . '/';
    }

    function writeToFile($file, $content)
    {
        if (($fileHandle = fopen($file, 'w')) === FALSE) {
            throw new Exception('Could not open file "' . $file . '".');
        }
        // write data to file
        if (fwrite($fileHandle, $content) === FALSE) {
            throw new Exception('Could not write to file "' . $file . '".');
        }
        // close file
        fclose($fileHandle);
    }
    
    function readFile($file)
    {
        if (file_exists($file)) {
            return file_get_contents($file);
        }
        else {
            throw new Exception('File "' . $file . '" does not exist.');
        }
    }

    function getFreeGraphId()
    {
        // read graph directory and sort by file names to get highest graph id
        $files = scandir($this->_graphDirectory);
        sort($files, SORT_NUMERIC);
        end($files);
        $highest = intval(current($files));
        return ++$highest;
    }        

    function storeGraph(Cicp_Graph $graphObject)
    {
        // store gdf file
        $file = $this->getGdfFilePath($graphObject);
        $this->writeToFile($file, $graphObject->toString());
        // store graph data
        $file = $this->getGraphFilePath($graphObject);
        $this->writeToFile($file, serialize($graphObject));
    }

    function readGraph($graphId)
    {
        $file = $this->_graphDirectory . $graphId;
        $data = unserialize($this->readFile($file));
        if ($data instanceof Cicp_Graph) {
            return $data;
        }
        else {
            throw new Exception('Graph data in ' . $file . ' seems to be corrupted.');
        }
    }

    function deleteGraph(Cicp_Graph $graph)
    {
        $file = $this->getGraphFilePath($graph);
        unlink($file);
    }

    function getGraphFilePath(Cicp_Graph $graph)
    {
        return $this->_graphDirectory . $graph->getId();
    }

    function getGdfFilePath(Cicp_Graph $graph)
    {
        return $this->_gdfDirectory . $graph->getId();
    }

    /**
     * delets all files in graph directory
     */
    function clearGraphDirectory()
    {
        foreach(glob($this->_graphDirectory . '*') as $f) {
            unlink($f);
        }  
    }

    function createDirectory($path)
    {
        if (!file_exists($path)) {
            // create dir recursively
            mkdir($path, 0777, TRUE);
        }
    }
}